/*
 * @Author: lx
 * @Date: 2025-03-21 21:26:38
 * @Description: antd-ProTable,自定义表头树形下拉框
 */
import { FilterFilled } from '@ant-design/icons';
import { useDeepCompareEffect } from '@ant-design/pro-components';
import { useClickAway } from 'ahooks';
import { Button, Dropdown, Tree } from 'antd';
import classnames from 'classnames';
import { useMemo, useRef, useState } from 'react';
import styles from './index.less';
import {
  DataNode,
  getChildKeys,
  getFullChildrenSelectedKey,
  getParentKeys,
} from './tools';

const treeData: DataNode[] = [
  {
    title: '0-0',
    key: '0-0',
    children: [
      {
        title: '0-0-0',
        key: '0-0-0',
        children: [
          { title: '0-0-0-0', key: '0-0-0-0' },
          { title: '0-0-0-1', key: '0-0-0-1' },
          { title: '0-0-0-2', key: '0-0-0-2' },
        ],
      },
      {
        title: '0-0-1',
        key: '0-0-1',
        children: [
          { title: '0-0-1-0', key: '0-0-1-0' },
          { title: '0-0-1-1', key: '0-0-1-1' },
          { title: '0-0-1-2', key: '0-0-1-2' },
        ],
      },
      {
        title: '0-0-2',
        key: '0-0-2',
      },
    ],
  },
  {
    title: '0-1',
    key: '0-1',
    children: [
      { title: '0-1-0-0', key: '0-1-0-0' },
      { title: '0-1-0-1', key: '0-1-0-1' },
      { title: '0-1-0-2', key: '0-1-0-2' },
    ],
  },
  {
    title: '0-2',
    key: '0-2',
  },
];

interface TableColumnFilterProps {
  value: Record<string, string[]>; // 传入一个对象，对象的key表示column的dataIndex，value表示选中的值
  columnDataIndex: string; // 组件渲染在哪一个column内
  onChange: (checkedObj: Record<string, string[]>) => void;
}

const TableColumnFilter: React.FC<TableColumnFilterProps> = (props) => {
  const { value = {}, columnDataIndex, onChange } = props;

  // 当前选中的数据
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);

  // 按钮控制
  const [open, setOpen] = useState(false);

  // 重置按钮是否可点
  const restButtonDisabled = useMemo(() => {
    return !checkedKeys?.length;
  }, [checkedKeys]);

  // 筛选图标是否选中
  const filterChecked = useMemo(() => {
    const valueKey = Object.keys(value)?.[0];
    if (
      valueKey === columnDataIndex &&
      (checkedKeys?.length || value[valueKey]?.length)
    ) {
      return true;
    }

    return false;
  }, [value, checkedKeys]);

  // 点击复选框的回调
  const onCheck = (checkedKeysValue: any) => {
    setCheckedKeys(checkedKeysValue);
  };
  // 点击文字的回调
  const onSelect = (_selectedKeysValue: any, info: any) => {
    const selectedKey = info?.node?.key;
    const selected = checkedKeys.includes(selectedKey);
    // 获取当前点击项的key的所有子集keys
    const childKeys = getChildKeys(selectedKey, treeData);
    // 选中
    if (!selected) {
      // 是否有父级key被选中
      const parentKeys = getFullChildrenSelectedKey(treeData, [
        selectedKey,
        ...childKeys,
        ...checkedKeys,
      ]);
      // 选中的父级key可能重复计算，这里就需要去重
      const uniqueArr = Array.from(
        new Set([selectedKey, ...childKeys, ...checkedKeys, ...parentKeys]),
      );
      setCheckedKeys(uniqueArr);
    } else {
      // 取消选中
      const parentKeys = getParentKeys(selectedKey, treeData);
      console.log({ parentKeys });
      setCheckedKeys(
        checkedKeys.filter(
          (i) => ![selectedKey, ...childKeys, ...parentKeys].includes(i),
        ),
      );
    }
  };

  // 确定的回调函数
  const onSubmit = () => {
    setOpen(false);
    onChange?.({ [columnDataIndex]: checkedKeys });
  };

  // 点击元素外层，关闭弹窗
  const ref = useRef(null);
  useClickAway(() => {
    setOpen(false);
  }, ref);

  useDeepCompareEffect(() => {
    // 判断传入的columnDataIndex和value的key值是否一致，一致则赋值checkedKeys，反之则置空
    const valueKey = Object.keys(value)?.[0];
    if (valueKey !== columnDataIndex) {
      setCheckedKeys([]);
    } else {
      setCheckedKeys(value?.[valueKey] || []);
    }
  }, [value]);

  return (
    <div className={styles.column_filter_dropdown} ref={ref}>
      <Dropdown
        open={open}
        getPopupContainer={(trigger) => trigger.parentElement || document.body}
        dropdownRender={() => (
          <div className={styles.filter_dropdown_wrap}>
            <Tree
              rootClassName={styles.filter_tree}
              checkable
              defaultExpandAll
              onCheck={onCheck}
              checkedKeys={checkedKeys}
              onSelect={onSelect}
              treeData={treeData}
            />
            <div
              style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
              }}
              className={styles.filter_tree_footer}
            >
              <Button
                type="link"
                size="small"
                disabled={restButtonDisabled}
                onClick={() => {
                  setCheckedKeys([]);
                }}
              >
                重置
              </Button>
              <Button type="primary" size="small" onClick={onSubmit}>
                确定
              </Button>
            </div>
          </div>
        )}
      >
        <div
          className={classnames([
            styles.filter_dropdown_box,
            {
              [styles.filter_dropdown_checked]: filterChecked,
            },
          ])}
          onClick={() => setOpen(!open)}
        >
          <FilterFilled />
        </div>
      </Dropdown>
    </div>
  );
};

export default TableColumnFilter;
